<template>
  <div>
    <div>
      <!-- 三级分类全局组件 -->
      <Category :scene="scene"></Category>
    </div>
    <el-card shadow="always" style="margin: 10px 0px">
      <div v-show="scene === 0">
        <el-button
          type="primary"
          size="default"
          @click="addAttr"
          icon="Plus"
          :disabled="!categoryStore.c3Id"
        >
          添加属性
        </el-button>
        <el-table border style="margin: 10px 0" :data="attrArr">
          <el-table-column
            label="序号"
            type="index"
            align="center"
            width="80px"
          ></el-table-column>
          <el-table-column
            label="属性名称"
            align="center"
            width="120px"
            prop="attrName"
          ></el-table-column>
          <el-table-column label="属性值名称">
            <template #="{ row }">
              <el-tag
                style="margin: 5px"
                v-for="item in row.attrValueList"
                :key="item.id"
                type="primary"
                effect="dark"
                closable
                @close=""
              >
                {{ item.valueName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="120px">
            <!-- row代表已有的属性对象attrArr -->
            <template #="{ row }">
              <!-- 修改已有属性的按钮 -->
              <el-button
                type="primary"
                size="small"
                @click="updateAttr(row)"
                icon="Edit"
              ></el-button>

              <el-popconfirm
                :title="`确认删除${row.attrName}?`"
                width="200px"
                @confirm="deleteAttr(row.id)"
              >
                <template #reference>
                  <el-button
                    type="primary"
                    size="small"
                    icon="Delete"
                  ></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-show="scene === 1">
        <!-- 展示添加属性与修改数据的结构 -->
        <el-form :inline="true">
          <el-form-item label="属性名称">
            <el-input
              placeholder="请你输入属性的名称"
              v-model="attrParams.attrName"
              clearable
              @change=""
            ></el-input>
          </el-form-item>
        </el-form>
        <el-button
          type="primary"
          :disabled="attrParams.attrName ? false : true"
          size="default"
          @click="addAttrValue"
          icon="Plus"
        >
          添加属性值
        </el-button>
        <el-button type="primary" size="default" @click="cancel">
          取消
        </el-button>
        <el-table
          border
          stripe
          :data="attrParams.attrValueList"
          style="margin: 10px 0"
        >
          <el-table-column
            label="序号"
            width="80px"
            type="index"
            align="center"
          ></el-table-column>
          <el-table-column label="属性值名称">
            <template #="{ row, $index }">
              <!-- ref获取实例，当变化时，加入数组中 -->
              <el-input
                :ref="(vc: any) => (inputArr[$index] = vc)"
                size="small"
                v-if="row.flag"
                placeholder="请输入属性值名称"
                v-model="row.valueName"
                @blur="toLook(row, $index)"
              ></el-input>
              <div v-else @click="toEdit(row, $index)">
                {{ row.valueName }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="属性值操作">
            <template #="{ $index }">
              <el-button
                type="primary"
                size="small"
                @click="attrParams.attrValueList.splice($index, 1)"
                icon="Delete"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          type="primary"
          size="default"
          @click="save"
          :disabled="attrParams.attrValueList.length > 0 ? false : true"
        >
          保存属性值
        </el-button>
        <el-button type="primary" size="default" @click="cancel">
          取消
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch, reactive, nextTick, onBeforeUnmount } from 'vue'
//引入已有属性与属性值接口
import {
  reqAttr,
  reqAddOrUpdateAttr,
  reqRemoveAttr,
} from '@/apis/product/attr/index'
import type {
  AttrResponseData,
  AttrValue,
  Attr,
} from '@/apis/product/attr/type'
//引入分类相关的仓库
import useCategoryStore from '@/store/modules/category'
import { ElMessage } from 'element-plus'
//使用仓库
let categoryStore = useCategoryStore()
//存储已有的属性与属性值
let attrArr = ref<Attr[]>([])
//定义卡片内容切换的变量,scene=0 显示table,scene=1显示添加与修改属性结构
let scene = ref<number>(0)
//收集新增的属性的数据
let attrParams = reactive<Attr>({
  attrName: '', //新增属性的名字
  attrValueList: [
    //新增属性值数组
  ],
  categoryId: '', //三级分类的ID
  categoryLevel: 3, //代表的是三级分类
})
//准备一个数组：将来存储对应的组件实例el-input
let inputArr = ref<any>([])

//删除某一个已有的属性方法回调
const deleteAttr = async (attrId: number) => {
  let res: any = await reqRemoveAttr(attrId)
  if (res.code === 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    //重新获取已有的属性值
    getAttr()
  } else {
    ElMessage({
      type: 'error',
      message: '删除失败',
    })
  }
}

//编辑模式
const toEdit = (row: AttrValue, $index: number) => {
  row.flag = true
  //nextTick，当响应式数据发生变化，获取更新的DOM(组件实例)

  nextTick(() => {
    inputArr.value[$index].focus()
  })
}

//观察模式
const toLook = (row: AttrValue, $index: number) => {
  //非法情况判断
  //非法情况1:判断是否为空
  if (row.valueName.trim() == '') {
    //删除对应属性值的元素
    attrParams.attrValueList.splice($index, 1)
    //提示信息
    ElMessage({
      type: 'error',
      message: '属性值不能为空',
    })
    return
  }

  //非法情况2：判断属性是否重复
  let repeat = attrParams.attrValueList.find((item) => {
    //切记排除自身的情况,把当前失去焦点属性值对象从当前数组扣除判断
    if (item !== row) {
      return item.valueName === row.valueName
    }
  })
  if (repeat) {
    ElMessage({
      type: 'error',
      message: '属性值不能重复',
    })

    return
  }
  //相应的属性值对象flag：变为false，展示div
  row.flag = false
}

//保存按钮的回调
const save = async () => {
  //发请求
  let res: any = await reqAddOrUpdateAttr(attrParams)
  if (res.code === 200) {
    scene.value = 0
    //提示信息
    ElMessage({
      type: 'success',
      message: attrParams.id ? '修改成功' : '添加成功',
    })
    //获取全部已有的属性与属性值
    getAttr()
  } else {
    ElMessage({
      type: 'error',
      message: attrParams.id ? '修改失败' : '添加失败',
    })
  }
}

//添加属性值按钮的回调
const addAttrValue = () => {
  // 检测数据是否重复,获取最后一个属性值，与整个列表item比较
  // 获取最后一个属性值
  let lastItem = attrParams.attrValueList[attrParams.attrValueList.length - 1]
  //生成新数组，不包括最后一个属性值
  let newArr = attrParams.attrValueList.slice(
    0,
    attrParams.attrValueList.length - 1,
  )
  //遍历新数组
  let repeat = newArr.find((item) => {
    return lastItem.valueName === item.valueName
  })
  if (repeat) {
    // ElMessage({
    //   type:'error',
    //   message:'属性值不能重复'
    // })
    return
  }

  // 点击添加属性值按钮，向数组添加一个属性值对象
  attrParams.attrValueList.push({
    valueName: '',
    flag: true, //控制每个属性值编辑模式与切换模式的切换
  })
  //获取最后一个el-input组件聚焦
  nextTick(() => {
    inputArr.value[attrParams.attrValueList.length - 1].focus()
  })
}

//取消按钮的回调
const cancel = () => {
  scene.value = 0
}

//添加属性按钮的回调
const addAttr = () => {
  //首先清空数组，再收集数据
  Object.assign(attrParams, {
    attrName: '', //新增属性的名字
    attrValueList: [
      //新增属性值数组
    ],
    //点击按钮收集新增属性的三级分类的id
    categoryId: categoryStore.c3Id, //三级分类的ID
    categoryLevel: 3, //代表的是三级分类
  })
  //切换添加与属性修改
  scene.value = 1
}

//table表格修改已有属性按钮的回调
const updateAttr = (row: Attr) => {
  scene.value = 1
  //将已有的属性对象赋值给attrParams对象
  //深拷贝避免bug
  Object.assign(attrParams, JSON.parse(JSON.stringify(row)))
}

//监听仓库三级分类ID的变化
watch(
  () => categoryStore.c3Id,
  () => {
    //清空上一次查询的属性与属性值
    attrArr.value = []
    //保证有三级分类才能发送请求
    if (!categoryStore.c3Id) {
      return
    }
    getAttr()
  },
)
//获取已有属性与属性值的方法
const getAttr = async () => {
  //获取分类ID
  const { c1Id, c2Id, c3Id } = categoryStore
  let res: AttrResponseData = await reqAttr(c1Id, c2Id, c3Id)
  if (res.code === 200) {
    attrArr.value = res.data
  }
}

//路由组件销毁时，清空分类相关数据
onBeforeUnmount(() => {
  categoryStore.$reset()
})
</script>

<style lang="scss" scoped></style>
